
#include "stdafx.h"
#include "Logutil.h"
#include <vector>
#include <string>
#include <cstring>
#include <strsafe.h>
#include <fstream>
#include <time.h>


namespace woe
{
		TimeStamp TimeStamp::_startStamp;

		TimeStamp::TimeStamp() 
		{
#ifdef WIN32
			//
			//	time is not accurate use win32 api later
			_seconds = (int)::time(NULL);
			_microSeconds = 0;
#else
			struct timeval tv;
			::gettimeofday(&tv, NULL);
			_seconds = tv.tv_sec;
			_microSeconds = tv.tv_usec;
#endif
		}

		TimeStamp::TimeStamp(unsigned int seconds, unsigned int microSeconds) :
		_seconds(seconds),
			_microSeconds(microSeconds) 
		{
		}


		void TimeStamp::format(std::string& fmt)const
		{
			struct std::tm currentTime;
			time_t t = getSeconds();
			localtime_s(&currentTime, &t);
			char formatted[100];
			StringCbPrintf( formatted, 
				100,
				TS("%04d-%02d-%02d %02d:%02d:%02d"), 
				currentTime.tm_year +1900, 
				currentTime.tm_mon +1,
				currentTime.tm_mday, 
				currentTime.tm_hour, 
				currentTime.tm_min, 
				currentTime.tm_sec );
			fmt = formatted;
		}

		const string& getLogLevelName(short lvl)
		{
			static std::vector<string> __log_level_names;
			static string __default_name = TS("unknown");
			if (__log_level_names.empty())
			{
				__log_level_names.push_back(TS("debug"));
				__log_level_names.push_back(TS("info"));
				__log_level_names.push_back(TS("warn"));
				__log_level_names.push_back(TS("error"));
				__log_level_names.push_back(TS("fatal"));
			}

			if (lvl>=0 && lvl<(int)__log_level_names.size())
			{
				return __log_level_names[lvl];
			}
			else
			{
				return __default_name;
			}
		}



#ifdef UNICODE
#define		atoint	_wtoi
#else
#define		atoint	atoi
#endif

		

		std::vector<string> LogLevelUtil::__log_level_names;

		const string& LogLevelUtil::getLogLevelName(short lvl)
		{

			static string __default_name = TS("unknown");
			if (__log_level_names.empty())
			{
				__log_level_names.push_back(TS("debug"));
				__log_level_names.push_back(TS("info"));
				__log_level_names.push_back(TS("warn"));
				__log_level_names.push_back(TS("error"));
				__log_level_names.push_back(TS("fatal"));
			}

			if (lvl>=0 && lvl<(int)__log_level_names.size())
			{
				return __log_level_names[lvl];
			}
			else
			{
				return __default_name;
			}
		}

		short	LogLevelUtil::getLogLevel(const string& lvlName)
		{
			if (__log_level_names.empty())
			{
				__log_level_names.push_back(TS("debug"));
				__log_level_names.push_back(TS("info"));
				__log_level_names.push_back(TS("warn"));
				__log_level_names.push_back(TS("error"));
				__log_level_names.push_back(TS("fatal"));
			}

			for (size_t i=0; i<__log_level_names.size(); i++)
			{
				if (lvlName == __log_level_names[i])
				{
					return short(i);
				}
			}

			return 0;
		}
}